<script setup lang="ts">
import { ref, onMounted, h } from 'vue'
import { Card, Table, Form, Input, Button, Space, DatePicker, Tag, message, Select } from 'ant-design-vue'
import { SearchOutlined, ReloadOutlined, EyeOutlined, UploadOutlined } from '@ant-design/icons-vue'
import type { TableColumnType } from 'ant-design-vue'
import { studentTaskApi } from '@/api/modules/studentTask'
import type { StudentTaskVO } from '@/types/task'
import { TaskDeadlineStatus, TaskSubmitStatus } from '@/types/task'
import { SubmissionStatus } from '@/types/taskSubmission'


import { useRouter } from 'vue-router'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');
const router = useRouter()

// 定义搜索表单类型
interface SearchForm {
  name: string;
  timeRange: [dayjs.Dayjs, dayjs.Dayjs] | null;
  status?: TaskSubmitStatus; // 改为使用 TaskSubmitStatus
}

const searchForm = ref<SearchForm>({
  name: '',
  timeRange: null,
  status: undefined,
})

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '已截止', value: TaskSubmitStatus.EXPIRED },
  { label: '待提交', value: TaskSubmitStatus.PENDING },
  { label: '待审核', value: TaskSubmitStatus.REVIEWING },
  { label: '已通过', value: TaskSubmitStatus.APPROVED },
  { label: '已驳回', value: TaskSubmitStatus.REJECTED }
]

// 表格数据
const loading = ref(false)
const tableData = ref<StudentTaskVO[]>([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total: number) => `共 ${total} 条记录`
})

// 表格列定义
const columns: TableColumnType[] = [
  {
    title: '任务名称',
    dataIndex: 'name',
    width: 200,
    align: 'center',
    ellipsis: true
  },
  {
    title: '截止时间',
    dataIndex: 'deadline',
    width: 180,
    align: 'center',

    customRender: ({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
  },
  {
    title: '状态',
    dataIndex: 'submitStatus', // 后端返回的状态字段
    align: 'center',
    width: 120,
    customRender: ({ text }: { text: TaskSubmitStatus }) => {
      const config = {
        [TaskSubmitStatus.EXPIRED]: { color: 'default', text: '已截止' },
        [TaskSubmitStatus.PENDING]: { color: 'warning', text: '待提交' },
        [TaskSubmitStatus.REVIEWING]: { color: 'processing', text: '待审核' },
        [TaskSubmitStatus.APPROVED]: { color: 'success', text: '已通过' },
        [TaskSubmitStatus.REJECTED]: { color: 'error', text: '已驳回' }
      }
      console.log(' config[text]?.color', config[text], text, config[text]?.text)
      return h(Tag, { color: config[text]?.color }, () => config[text]?.text)
    }
  },
  {
    title: '提交时间',
    dataIndex: 'submissionTime',
    align: 'center',
    width: 180,
    customRender: ({ text }) => text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '-'
  },
  {
    title: '创建老师',
    dataIndex: 'teacherName',
    width: 150,
    align: 'center',
    ellipsis: true
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    align: 'center',
    fixed: 'right',
    customRender: ({ record }) => renderActionButtons(record)
  }
]

// 获取任务列表
const fetchList = async () => {
  loading.value = true
  try {
    const data = await studentTaskApi.getTaskPage({
      name: searchForm.value.name,
      status: searchForm.value.status,
      startTime: searchForm.value.timeRange?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
      endTime: searchForm.value.timeRange?.[1]?.format('YYYY-MM-DD HH:mm:ss'),
      page: pagination.value.current - 1,
      size: pagination.value.pageSize
    })
    
    tableData.value = data.content
    pagination.value.total = data.totalElements
  } catch (error) {
    console.error('获取任务列表失败:', error)
    message.error(error||'获取任务列表失败，请检查 API 是否正常工作。')
  } finally {
    loading.value = false
  }
}

// 处理表格变更
const handleTableChange = (newPagination: any, filters: any, sorter: any) => {
  pagination.value.current = newPagination.current
  pagination.value.pageSize = newPagination.pageSize
  fetchList()
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  fetchList()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    name: '',
    timeRange: null,
    status: undefined
  }
  pagination.value.current = 1
  fetchList()
}

// 查看详情
const handleViewDetail = (record: StudentTaskVO) => {
  router.push(`/student/task/detail/${record.id}`)
}

// 提交任务
const handleSubmit = (record: StudentTaskVO) => {
  router.push(`/student/task/submit/${record.id}`)
}

// 修改操作列的按钮显示逻辑
const renderActionButtons = (record: StudentTaskVO) => {
  const buttons = [
    h(Button, {
      type: 'link',
      onClick: () => handleViewDetail(record)
    }, () => [
      h(EyeOutlined),
      '查看'
    ])
  ]

  // 只有在特定状态下才显示提交/修改按钮
  if ([TaskSubmitStatus.PENDING, TaskSubmitStatus.REJECTED].includes(record.submitStatus)) {
    buttons.push(
      h(Button, {
        type: 'link',
        onClick: () => handleSubmit(record)
      }, () => [
        h(UploadOutlined),
        record.submitStatus === TaskSubmitStatus.REJECTED ? '修改' : '提交'
      ])
    )
  }

  return h(Space, {}, buttons)
}

onMounted(() => {
  fetchList()
})
</script>

<template>
  <div class="student-task">
    <Card>
      <!-- 搜索表单 -->
      <Form layout="inline">
        <Form.Item label="任务名称">
          <Input
            v-model:value="searchForm.name"
            placeholder="请输入任务名称"
            allow-clear
          />
        </Form.Item>
        <Form.Item label="时间范围">
          <DatePicker.RangePicker
            v-model:value="searchForm.timeRange"
            :locale="locale"
            :placeholder="['开始时间', '结束时间']"
          />
        </Form.Item>
        <Form.Item label="状态">
          <Select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            style="width: 130px;"
            allowClear
          >
            <Select.Option v-for="option in statusOptions" 
              :key="option.value" 
              :value="option.value"
            >
              {{ option.label }}
            </Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" @click="handleSearch">
              <template #icon><SearchOutlined /></template>
              搜索
            </Button>
            <Button @click="handleReset">
              <template #icon><ReloadOutlined /></template>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>

      <!-- 任务列表 -->
      <Table
        :columns="[
          ...columns.filter(col => col.key !== 'action'),
          {
            title: '操作',
            key: 'action',
            width: 180,
            align: 'center',
            fixed: 'right',
            customRender: ({ record }) => renderActionButtons(record)
          }
        ]"
        :data-source="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #emptyText>
          <div class="empty-wrapper">
            暂无任务
          </div>
        </template>
      </Table>
    </Card>
  </div>
</template>

<style lang="less" scoped>
.student-task {
  :deep(.ant-form) {
    margin-bottom: 16px;
  }

  .empty-wrapper {
    padding: 32px 0;
    text-align: center;
    color: rgba(0, 0, 0, 0.25);
  }
}
</style> 